#include <iostream>
#include <pthread.h>
#include <string>
#include "Socket.hpp"

class ThreadData
{
public:
    ThreadData(TcpServer* tcpserver, Net_Work::Socket *sockp)
        :_this(tcpserver), _sockp(sockp)
    {}
public:
    TcpServer *_this;
    Net_Work::Socket *_sockp;
};

class TcpServer
{
public:
    TcpServer(uint16_t port)
        :_port(port), _listensocket(new Net_Work::TcpSocket())
    {
        _listensocket->BuildListenSocketMethod(_port, Net_Work::default_backlog);
    }

    static void* ThreadRun(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);

        char inbufferstream[4096];
        while(true)
        {
            bool ok = true;
            recv(td->_sockp->GetSocket(), inbufferstream, sizeof(inbufferstream) - 1, 0);
        }
    }

    void Loop()
    {
        while(true)
        {
            std::string peerip;
            uint16_t peerport;
            Net_Work::Socket* newsock = _listensocket->AcceptConnection(&peerip, &peerport);
            if(newsock)
                continue;
            ThreadData *td = new ThreadData(this, newsock);
            pthread_t pid;
            pthread_create(&pid, nullptr, ThreadRun, (void *)td);
        }
    }
private:
    uint16_t _port;
    Net_Work::Socket *_listensocket;
};
